<template>
    <el-container v-loading="loading" element-loading-text="拼命加载中...">
        <el-main class="nopadding" v-if="isSetting == false">
            <el-empty description="暂无数据源信息" :image-size="100" style="margin-top: 200px">
                <el-button type="primary" text @click="dataSourceSetting">立即设置</el-button>
            </el-empty>
        </el-main>
        <el-main class="nopadding" v-else-if="isSetting == true">
            <el-container>
                <el-header>
                    <div class="left-panel">
                        <el-button-group>
                            <el-button type="primary" icon="el-icon-plus" @click="addData">添加</el-button>
                            <el-button icon="el-icon-upload" @click="importData">导入</el-button>
                            <el-button icon="el-icon-download" @click="exportData">导出</el-button>
                            <el-button icon="el-icon-printer">打印</el-button>
                            <el-button type="danger" plain icon="el-icon-delete">删除</el-button>
                        </el-button-group>
                    </div>
                    <div class="right-panel">
                        <div class="right-panel-search">
                            <template v-if="searchOption.length > 0">
                                <el-input ref="searchInput" v-model="search.keyword" minlength="1" maxlength="20" placeholder="请输入关键字" clearable>
                                    <template #prepend v-if="searchOption.length > 1">
                                        <el-select v-model="search.type"  placeholder="请选择..." style="width: 100px">
                                            <el-option :label="item.label" :value="item.value" v-for="(item, index) in searchOption"></el-option>
                                        </el-select>
                                    </template>
                                </el-input>
                                <el-button type="primary" icon="el-icon-search" @click="btnSearch"></el-button>
                            </template>
                            <el-button type="text" icon="el-icon-setting" @click="dataSourceSetting">设置</el-button>
                        </div>
                    </div>
                </el-header>
                <el-main class="nopadding">
                    <jd-table ref="table" tableName="listCustomColumn" @change-page="changePage" :dataTotal="total" :data="dataList" :column="list.column" row-key="id" stripe>
                        <el-table-column type="selection" width="50"></el-table-column>
                        <template #progress="scope">
                            <el-progress :percentage="scope.row.progress" />
                        </template>
                        <el-table-column label="操作" fixed="right" align="center" width="150">
                            <template #default="scope">
                                <el-button-group>
                                    <el-button text type="primary" class="button">编辑</el-button>
                                    <el-popconfirm title="确定要删除吗？" @confirm="delData(scope)">
                                        <template #reference>
                                            <el-button text type="primary" class="button">删除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </el-button-group>
                            </template>
                        </el-table-column>
                    </jd-table>
                </el-main>
            </el-container>
        </el-main>
    </el-container>

    <dataSource-dialog ref="dataSourceDialog" v-if="dialog.datasource" @close="refresh" @success="handleSuccess" @closed="dialog.datasource = false"></dataSource-dialog>
    <fileUpload-dialog ref="FileUploadDialog" v-if="showUploadDialog" @closed="showUploadDialog = false" @refresh="getDataList" :fieldList="allFieldList" :modelId="this.modelId"></fileUpload-dialog>
    <dataAdd-dialog ref="dataAddDialog" v-if="showDataAddDialog" @closed="showDataAddDialog = false" @refresh="getDataList"></dataAdd-dialog>
</template>

<script>
import dataSourceDialog from './components/dataSource.vue';
import fileUploadDialog from './components/file-upload.vue';
import dataAddDialog from './components/data-add.vue';

export default {
    name: 'dataCenter',
    components: {
        dataSourceDialog,
        fileUploadDialog,
        dataAddDialog
    },
    data() {
        return {
            loading: true,
            dialog: {
                datasource: false
            },
            appId: null,
            modelId: null,
            fields: [],
            dataList: [],
            isSetting: undefined,
            total: 0,
            params: {
                // 模型ID
                modelId: null,
                // 字段集合
                fields: [],
                // 规则列表
                screenList: [],
                // 当前页面
                pageNum: 1,
                // 页面大小
                pageSize: 20
            },
            list: {
                column: []
            },
            search: {
                keyword: '',
                type: ''
            },
            searchOption: [],
            allFieldList: [],
            buttonConfig: null,
            showUploadDialog: false,
            showDataAddDialog: false
        };
    },
    created() {
        this.appId = this.$route.query.appId;
        // 自动展开菜单
        this.$store.commit('TOGGLE_IsCollapse', false);
        // 加载配置信息
        this.getSetting();
    },
    methods: {
        // 添加单条数据
        addData() {
            this.showDataAddDialog = true;
            this.$nextTick(() => {
                this.$refs.dataAddDialog.open(this.list.column, this.modelId);
            });
        },
        // 导入数据
        importData() {
            this.showUploadDialog = true;
            this.$nextTick(() => {
                this.$refs.FileUploadDialog.open();
            });
        },
        // 导出数据
        async exportData() {
            const res = await this.$API.system.dataList.modelExport.post(this.params, { responseType: 'blob' });
            console.log(res, 'res');
            let blob = new Blob([res], {
                type: 'application/vnd.ms-excel'
            });
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(blob);
            var fileName = new Date().getTime() / 1000;
            downloadElement.href = href;
            downloadElement.download = fileName + '.xlsx';
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(href);
        },
        // 删除数据
        async delData(scope) {
            const data = {
                modelId: this.modelId,
                value: JSON.stringify({ id: scope.row.id, del_flag: '1' })
            };
            const res = await this.$API.system.dataList.modelSave.post(data);
            if (res.code === 200 || res.code === 0) {
                this.$message.success({
                    message: res.msg
                });
                this.getDataList();
            } else {
                this.$message.error({
                    message: res.msg
                });
            }
        },
        // 数据列表配置
        async getSetting() {
            var res = await this.$API.system.dataList.getConfig.get(this.appId);
            if (res.code == 200 && res.data != null) {
                var jsonFields = JSON.parse(res.data.fieldConfig);
                this.allFieldList = JSON.parse(res.data.fieldConfig);
                this.modelId = res.data.modelId;
                this.buttonConfig = res.data.buttonConfig;
                this.fields = [];
                this.list.column = [];
                this.searchOption = [];
                this.list.column.push({
                    label: 'ID',
                    prop: 'id',
                    width: '180',
                    sortable: false
                });
                jsonFields.map((item) => {
                    this.list.column.push({
                        label: item.label,
                        prop: item.prop,
                        width: item.width,
                        hide: item.hide,
                        query: item.query,
                        sortable: item.sortable,
                        fixed: item.fixed,
						control:item.control
                    });
                    this.fields.push({
                        field: item.prop,
                        comment: item.label,
                        type: item.type,
                        length: item.width,
                        hide: item.hide,
                        query: item.query,
                        sortable: item.sortable,
                        fixed: item.fixed,
						control:item.control
                    });
                    if (item.query) {
                        this.searchOption.push({
                            label: item.label,
                            value: item.prop
                        });
                    }
                });
                // 加载数据列表
                await this.getDataList();

                this.isSetting = true;
                this.loading = false;
            } else {
                // 弹出配置窗口
                this.dataSourceSetting();
                this.isSetting = false;
                this.loading = false;
            }
        },
        // 数据源配置
        dataSourceSetting() {
			this.dialog.datasource = true;
            this.$nextTick(() => {
                this.$refs.dataSourceDialog.open(this.appId, this.modelId, this.fields, this.buttonConfig);
            });
        },
        // 设置完成后回调
        async handleSuccess(modelId, jsonFields) {
            this.isSetting = true;
            this.modelId = modelId;

            this.fields = [];
            this.list.column = [];
            this.searchOption = [];
            this.list.column.push({
                label: 'ID',
                prop: 'id',
                width: '180',
                sortable: false
            });
            jsonFields.map((item) => {
                this.list.column.push({
                    label: item.label,
                    prop: item.prop,
                    width: item.width,
                    hide: item.hide,
                    query: item.query,
                    sortable: item.sortable,
                    fixed: item.fixed,
					control:item.control
                });
                this.fields.push({
                    field: item.prop,
                    comment: item.label,
                    type: item.type,
                    length: item.width,
                    hide: item.hide,
                    query: item.query,
                    sortable: item.sortable,
                    fixed: item.fixed,
					control:item.control
                });
                if (item.query) {
                    this.searchOption.push({
                        label: item.label,
                        value: item.prop
                    });
                }
            });

            // 加载数据列表
            await this.getDataList();
        },
        // 根据字段获取数据
        async getDataList() {
            this.dataList = [];
            this.params.modelId = this.modelId;
            this.params.fields = this.fields;
            const res = await this.$API.app.model.queryPage.post(this.params);
            if (res.code == 200) {
                this.dataList = res.data.rows;
                this.total = res.data.total;
            }
        },
        changePage(pageNum, pageSize) {
            this.params.pageNum = pageNum;
            this.params.pageSize = pageSize;
            this.getDataList();
        },
        // 搜索信息
        btnSearch() {
            this.params.screenList = [];

            var field = this.search.type;
            if (this.searchOption.length > 1) {
                if (this.search.type == '') {
                    this.$message.error('请先设置一个查询条件哦');
                    return;
                }
            } else {
                field = this.searchOption[0].value;
            }

            var keyword = this.search.keyword;
            var searchItem = {
                logic: 'AND',
                field: field,
                rule: 'LIKE',
                value: keyword
            };
            if (keyword != '') {
                this.params.screenList.push(searchItem);
            }
            // 获取数据列表
            this.getDataList();
        }
    }
};
</script>

<style lang="scss"></style>
